package blog;

import com.sun.xml.internal.ws.client.dispatch.PacketDispatch;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class PublishArticle implements Action {
    @Override
    public void run() {
        if (!User.isLogined()) {
            System.out.println("需要先登录才能操作该功能");
            return;
        }
        //和用户注册基本一致
        //获取用户的输入
        //根据当前用户，获取作者id
        //通过调用函数，获取当前时间
        System.out.println("发表中......");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入文章标题>");
        String title = scanner.nextLine();
        System.out.println("请输入正文>");
        String content = scanner.nextLine();
        int authorId = User.getCurrentUser().id;
        Date publishedAt = new Date();  //当前时间
        //publishedAt 现在是date对象，把date对象format成String格式
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String publishedAtStr = format.format(publishedAt);

        //信息已经获取完全，通过jdbc完成insert操作
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "insert into articles (author_id,title,published_at,content) values(?,?,?,?)";
            try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                preparedStatement.setInt(1, authorId);
                preparedStatement.setString(2, title);
                preparedStatement.setString(3, publishedAtStr);
                preparedStatement.setString(4, content);

                preparedStatement.executeUpdate();

                System.out.println("《" + title + "》发表成功！");
            }
        } catch (SQLException e) {
            System.out.println("错误:" + e.getMessage());
        }
    }
}
